#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
财联社电报数据Web展示应用
"""

from flask import Flask, render_template, jsonify, request
import os
from datetime import datetime
import argparse
from core.config import PG_HOST, PG_PORT, PG_DB_NAME as PG_DATABASE, PG_USER, PG_PASSWORD, WECHAT_ENABLED as CONFIG_WECHAT_ENABLED
from web.web_config import web_config

try:
    from database.pg_models import PostgresTelegramDatabase
    PSYCOPG2_AVAILABLE = True
except ImportError:
    print("错误: 无法导入PostgresTelegramDatabase类")
    PostgresTelegramDatabase = None
    PSYCOPG2_AVAILABLE = False

try:
    from core.local_wechat_notifier import LocalWeChatNotifier, local_wechat_notifier
    WECHAT_NOTIFIER_AVAILABLE = True
except ImportError:
    print("警告: 无法导入微信推送模块")
    LocalWeChatNotifier = None
    local_wechat_notifier = None
    WECHAT_NOTIFIER_AVAILABLE = False

# 获取当前文件所在目录的绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
# 使用绝对路径设置模板和静态文件夹
templates_dir = os.path.join(current_dir, '..', 'templates')
static_dir = os.path.join(current_dir, '..', 'static')
app = Flask(__name__, template_folder=templates_dir, static_folder=static_dir)

# 只使用PostgreSQL数据库
pg_db = None

# 初始化数据库连接
if PostgresTelegramDatabase and PSYCOPG2_AVAILABLE:
    print("使用PostgreSQL数据库...")
    pg_db = PostgresTelegramDatabase()
else:
    print("错误: PostgreSQL功能不可用（psycopg2模块缺失）")
    print("请安装psycopg2-binary以启用PostgreSQL功能: pip install psycopg2-binary")
    raise ImportError("PostgreSQL功能不可用")

def get_telegrams(limit=50):
    """从PostgreSQL数据库获取电报数据"""
    try:
        if pg_db:
            # 使用PostgreSQL数据库的正确方法
            return pg_db.get_latest_telegrams(limit)
        else:
            return []
    except Exception as e:
        print(f"获取电报数据时出错: {e}")
        return []

@app.route('/')
def index():
    """主页 - 使用调试版本"""
    return render_template('debug_index.html')

@app.route('/api/telegrams')
def api_telegrams():
    """API接口，返回JSON格式的电报数据"""
    # 获取参数
    limit = request.args.get('limit', 50, type=int)
    telegrams = get_telegrams(limit)
    return jsonify(telegrams)

@app.route('/api/stats')
def api_stats():
    """API接口，返回PostgreSQL数据库统计数据"""
    try:
        if pg_db:
            # 使用PostgreSQL数据库的正确方法
            total_count = pg_db.get_telegram_count()
            latest_telegrams = pg_db.get_latest_telegrams(1)
            latest_time = latest_telegrams[0]['time'] if latest_telegrams else None
            return jsonify({'total_count': total_count, 'latest_time': latest_time})
        else:
            return jsonify({'total_count': 0, 'latest_time': None})
    except Exception as e:
        print(f"获取统计数据时出错: {e}")
        return jsonify({'error': str(e)})

# 添加一个简单的测试路由
@app.route('/test')
def test():
    return "Web应用运行正常！"

def run_web_app():
    """运行Web应用程序"""
    # 确保模板和静态文件目录存在
    if not os.path.exists('templates'):
        os.makedirs('templates')
    if not os.path.exists('static'):
        os.makedirs('static')
    
    print("=== 财联社电报Web界面 ===")
    print("Web应用已启动，访问地址: http://localhost:5000")
    print("按 Ctrl+C 停止Web应用")
    
    app.run(host='0.0.0.0', port=5000, debug=True)

# === 微信推送控制API ===
@app.route('/api/wechat_config', methods=['GET'])
def get_wechat_config():
    """获取微信推送配置"""
    try:
        config = web_config.get_full_config()
        config['notifier_available'] = WECHAT_NOTIFIER_AVAILABLE
        config['system_wechat_enabled'] = CONFIG_WECHAT_ENABLED
        return jsonify(config)
    except Exception as e:
        print(f"获取微信配置时出错: {e}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/wechat_config', methods=['POST'])
def update_wechat_config():
    """更新微信推送配置"""
    try:
        data = request.json
        if 'wechat_push_enabled' in data:
            web_config.set_wechat_push_enabled(data['wechat_push_enabled'])
        if 'target_groups' in data:
            web_config.set_target_groups(data['target_groups'])
        
        return jsonify({
            'success': True,
            'config': web_config.get_full_config()
        })
    except Exception as e:
        print(f"更新微信配置时出错: {e}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/wechat_push/test', methods=['POST'])
def test_wechat_push():
    """测试微信推送功能"""
    try:
        if not WECHAT_NOTIFIER_AVAILABLE:
            return jsonify({'success': False, 'error': '微信推送模块不可用'})
        
        # 确保微信推送已在Web配置中启用
        if not web_config.get_wechat_push_enabled():
            return jsonify({'success': False, 'error': '微信推送未在Web配置中启用'})
        
        # 获取目标群组
        groups = web_config.get_target_groups()
        if not groups:
            return jsonify({'success': False, 'error': '未设置目标推送群'})
        
        # 准备测试消息
        test_message = "【财联社电报】测试消息\n这是一条来自Web界面的测试消息，\n说明微信推送功能正常工作。\n测试时间: " + datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
        # 向每个群组发送测试消息
        results = []
        for group in groups:
            if local_wechat_notifier:
                success, msg = local_wechat_notifier.send_message_to_group(group, test_message)
                results.append({
                    'group': group,
                    'success': success,
                    'message': msg
                })
            else:
                results.append({
                    'group': group,
                    'success': False,
                    'message': '微信通知器未初始化'
                })
        
        all_success = all(r['success'] for r in results)
        return jsonify({
            'success': all_success,
            'results': results
        })
    except Exception as e:
        print(f"测试微信推送时出错: {e}")
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    run_web_app()